import { PassportStrategy } from "@nestjs/passport";
import { InjectRepository } from "@nestjs/typeorm";
import { User } from "../user/entities/user.entity";
import { Repository } from "typeorm";
import { IStrategyOptions, Strategy } from "passport-local";
import { BadRequestException } from "@nestjs/common";
import * as bcrypt from "@node-rs/bcrypt";


// 用户名密码校验
export class LocalStrategy extends PassportStrategy(Strategy, "local") {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>
  ) {
    super({
      usernameField: "username",
      passwordField: "password",
    } as IStrategyOptions);
  }

  async validate(username: string, password: string) {
    
    // 根据用户名查找用户
    const user = await this.userRepository
      .createQueryBuilder("user")
      .addSelect("user.password")
      .where("user.username=:username", { username })
      .getOne();
    if (!user) {
      throw new BadRequestException("用户名不正确！");
    }
    // console.log("user",user);
    // console.log("password",password);
    const isValid = await bcrypt.compare(password, user.password)

    if (!isValid) {
      throw new BadRequestException("密码错误！");
    }

    return user;
  }

}



